import React, {Component} from 'react';
import {connect} from "react-redux"
class About extends Component {

	componentDidUpdate(){
		localStorage.setItem("mes",JSON.stringify(this.props.cartList))
	}


	allCount(){
		var count=0;
		for(var i in this.props.cartList){
			count+=this.props.cartList[i].count
		}
		return count
	}

	allPrice(){
		var total=0;
		for(var i in this.props.cartList){
			total+=this.props.cartList[i].count*this.props.cartList[i].price
		}
		return total
	}
	render() {
		return (
			<div>
				<table className="table table-hover">
					<thead>
						<tr>
							<th>id</th>
							<th>名称</th>
							<th>价格</th>
							<th>数量</th>
							<th>小计</th>
							<th>Actions</th>
						</tr>
					</thead>
					<tbody>
					{
						this.props.cartList.map(item=>{
							return(
								<tr key={item.id}>
									<td>{item.id}</td>
									<td>{item.name}</td>
									<td>{item.price}</td>
									<td>
										{
											this.props.cartList.find(val=>val.id===item.id)?
												item.count:""
										}
									</td>
									<td>{item.count*item.price}</td>
									<td>
										<button type="button" className="btn btn-info" onClick={()=>this.props.reduceCount(item.id)}>-</button>
										<button type="button" className="btn btn-warning" onClick={()=>this.props.addCount(item.id)}>+</button>
										<button type="button" className="btn btn-danger"  onClick={()=>this.props.remove(item.id)}>×</button>
									</td>
								</tr>
							)
						})
					}
					</tbody>
				</table>
				<div>
					<h3>总数{this.allCount()}</h3>
					<h3>总价{this.allPrice()}</h3>
					<h3><button className="btn btn-danger"  onClick={()=>this.props.delAll()}>清空购物车</button></h3>
				</div>
			</div>
		);
	}
}
function mapState(state,action) {
	return {
		cartList:state.cartList
	}
}
function mapAction(dispatch) {
	return{
		addCount: id=>dispatch({
			type:"ADD_COUNT",
			id
		}),
		reduceCount:id=>dispatch({
			type:"REDUCE_COUNT",
			id
		}),
		remove:id =>dispatch({
			type:"REMOVE",
			id
		}),
		delAll: () =>dispatch({
			type:"DELALLS"
		})
	}
}
export default connect(mapState,mapAction)(About);